package com.xm.apd.nettyclient.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by XMclassmate on 2017/12/18.
 */

public class ClientMsgHandler extends SimpleChannelInboundHandler<Message> {
    static ChannelHandlerContext chc;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        System.out.println("nettyclient: channelRead0"+Thread.currentThread().getName());
        try{
            System.out.println("nettyClient type:"+msg.getType());
            System.out.println("nettyClient bytes:"+new String(msg.getBytes()));
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("nettyclient: channelactive"+Thread.currentThread().getName());
        chc = ctx;
        byte[] bs = "我连上了".getBytes();
        chc.writeAndFlush(new Message((byte) 1,bs.length,bs));
    }

    static int count;
    public static void send(String str){
        System.out.println("nettyclient: send"+Thread.currentThread().getName());
        if (chc == null)
            return;
        byte[] bs = ("我是客户端"+count++).getBytes();
        chc.writeAndFlush(new Message((byte) 1,bs.length,bs));
    }
}
